import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag, formatTime } from 'services/utils'
import { Form, Input, DatePicker, Select, Button, message } from 'antd'
import ReactEcharts from 'echarts-for-react'
import echarts from 'echarts'
import { protoActions } from 'reduxs'
import _ from 'lodash'
import moment from 'moment'

const accessFlag = getPageFlag('/proto-chart/online', 'access')
const roomFlag = getPageFlag('/proto-chart/online', 'room')
const FormItem = Form.Item
const Option = Select.Option

@connect(
  state => ({
    auth                : state.Passport.auth,
    rtsp_key            : state.Passport.rtsp_key,
    postDataPending     : state.Proto.postDataPending,
    postDataError       : state.Proto.postDataError,
    postDataMessage     : state.Proto.postDataMessage,
    postDataProto       : state.Proto.postDataProto,
    rooms               : state.Proto.rooms,
    postData            : state.Proto.postData,
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
export default class Online extends PureComponent {

  constructor (props) {
    super(props)
  }

  componentDidMount () {
    this.props.actions.getlist()
  }
  
  componentWillReceiveProps (nextProps) {
    const { postDataError, postDataMessage, postDataProto, rtsp_key } = nextProps
    if (rtsp_key !== this.props.rtsp_key) {
      return
    }
  }

  render () {
    const { location, auth, postDataPending, rooms, postData, postDataProto } = this.props
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '数据图表类' },
        { name: '在线玩家统计' }
      ],
    }
    let proto = postDataProto === 'room-online' ? postDataProto : 'online'
    let PostData = null
    let PostOptions = {}
    let onlineData = null
    if (_.has(postData, proto)) {
      PostData = postData[proto]
      PostOptions = PostData.opts
      onlineData = PostData.data
      _.isArray(onlineData) && onlineData.sort()
    }
    const chartData = getChartData(onlineData || [])
    this.registerTheme()
    const echartsOpts = this.getEchartOtion(chartData)
    let isRoom = !getFlagValue(auth, roomFlag.value, null)
    return (
      <CoreLayout {...options}>
        <AdvancedSearchForm 
          onSubmit={this.handleSubmit}
          loading={postDataPending}
          rooms={isRoom ? rooms : null}
          Options={PostOptions}
          />
        
        <ReactEcharts
          option={echartsOpts}
          theme="online_theme"
          style={{ height: 600 }} 
        />
      </CoreLayout>
    )
  }

  handleSubmit = (values) => {
    let proto = _.isEmpty(values.roleId) ? 'online' : 'room-online'
    this.props.actions.postData(proto, values, this.props.rtsp_key)
  }

  registerTheme () {
    echarts.registerTheme('online_theme', {
      backgroundColor: '#fff'
    })
  }

  getEchartOtion = (data) => ({
    title: {
      text: '在线走势图',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer : { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    legend: {
      //data: _.map(roomOpts, 'name')
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
        type : 'category',
        boundaryGap : false,
        //splitLine: {show:false},
        data : data && _.map(data, 'time')//.slice(0, 9)
    },
    yAxis: {
        type : 'value',
    },
    series: [
      {
        name: '在线人数',
        type: 'line',
        smooth: true,
        data : data && _.map(data, 'value')
      }
    ]
  })
}

@Form.create()
class AdvancedSearchForm extends PureComponent {

  static propTypes = {
    Options: PropTypes.object,
    onSubmit: PropTypes.func,
    loading: PropTypes.bool,
    rooms: PropTypes.object,
  }
  
  static defaultProps = {
    Options: null,
    onSubmit: () => null,
    loading: false,
    rooms: null
  }

  constructor (props) {
    super(props)
  }

  render () {
    const { form, loading, rooms, Options } = this.props
    const { getFieldDecorator } = form
    let begin = moment()
    let roleId = ''
    if (_.has(Options, 'begin')) {
      begin = moment(Options['begin'])
    }
    if (_.has(Options, 'roleId')) {
      roleId = Options['roleId']
    }
    return (
      <Form
        className="ant-advanced-search-form"
        onSubmit={this.handleSubmit}
        >
        <div className="content">
          <FormItem 
            //label={(<span style={{ width: 80, display: 'inline-block' }}>时间点</span>)}
            >
            {getFieldDecorator('begin', {
              rules: [
                { required: true, message: `请选择时间点!` }
              ],
              initialValue: begin
            })(
              <DatePicker />
            )}
          </FormItem>
          <FormItem 
            //label={(<span style={{ width: 80, display: 'inline-block' }}>房间</span>)}
            >
            {getFieldDecorator('roleId', {
              initialValue: roleId
            })(
              <Select style={{ marginLeft: 10, width: 150 }}>
                <Option value="">大厅</Option>
                {_.keys(rooms).map((item, i) => {
                  return (
                    <Option key={i} value={item}>{rooms[item]}</Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
          <FormItem style={{ marginLeft: 20 }}>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading} 
              >
              查询
            </Button>
          </FormItem>
        </div>
      </Form>
    )
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (_.has(values, 'begin')) {
          values['begin'] = moment(values['begin']).format('YYYY-MM-DD')
        }
        this.props.onSubmit(values)
      }
    })
  }
}

const getChartData = (data, options = null) => {
  let chartData = []
  if (!_.isArray(data)) return []
  for (let item of data) {
    let { time, value } = _.zipObject(['time', 'value'], item.split(';'))
    chartData.push({ time, value })
  }
  return chartData
}